from config import webase_host
from results import *
from utils import common_utils
from flask import jsonify
from models.user import User
from models.tx_raw_data import TxRawData
import requests
from decimal import Decimal
from datetime import datetime


def home_page_query():
    """_summary_
    1. 获取区块高度
    2. 获取用户数量
    3. 获取最新交易内容（获取最后10条数据）
    """
    
    # 1. 获取区块高度
    url = "http://%s:5002/WeBASE-Front/1/web3/blockNumber" %(webase_host)

    payload = {}
    headers = {}

    response = requests.request("GET", url, headers=headers, data=payload)
    height = response.text
    
    # 2. 获取用户数量
    get_user_count = User.query.filter_by().count()
    
    # 3. 获取最新交易信息
    query_res = TxRawData.query.order_by(TxRawData.pk_id.desc()).limit(10)
    tx_list = []
    for i in query_res:
        tx_list.append(query_set_to_dict(i))
    
    res_dict = {
        "height": height,
        "user_count": get_user_count,
        "tx_list":  tx_list
    }
    return gen_result(200, res_dict)

def query_set_to_dict(obj, conv=False):
    """
    Serialize SQLAlchemy Query Set to Dict
    conv: 是否将datetime转换成google.protobuf的Timestamp, true:是，false:否
    """
    obj_dict = {}
    for column in obj.__table__.columns.keys():
        val = getattr(obj, column)
        if isinstance(val, Decimal):
            val = float(val)
        if isinstance(val, datetime):
            if conv:
                val = Timestamp(seconds=int(val.timestamp()))
            else:
                val = val.strftime("%Y-%m-%d %H:%M:%S")
        obj_dict[column] = val
    return obj_dict